//
//  YCAdView.m
//  Test
//
//  Created by tangkexiong on 16/4/14.
//  Copyright © 2016年 tangkexiong. All rights reserved.
//

#import "YCAdView.h"

#define kDuration 0.3f
#define kHeightPageControl 20.f
#define kMaxDistanceForResponde 100.f


#pragma mark - YCAdView

@interface YCAdView()<UIGestureRecognizerDelegate> {
    NSInteger _numberOfItems;   /// 图片数量
}

@property (nonatomic, strong) UIPanGestureRecognizer *panGesture;   /// 滑动手势
@property (nonatomic, strong) UITapGestureRecognizer *tapGesture;   /// 点击手势

@property (nonatomic, strong) UIImageView *leftImgView;             /// 左侧的图片控件
@property (nonatomic, strong) UIImageView *rightImgView;            /// 右侧的图片控件
@property (nonatomic, strong) UIImageView *curImgView;              /// 当前展示的图片控件
@property (nonatomic, strong) UIPageControl *pageControl;           /// 分页指示器
@property (nonatomic, strong) NSTimer *timer;                       /// 轮播定时器

@end

@implementation YCAdView

#pragma - UIView

- (void)willMoveToSuperview:(UIView *)newSuperview {
    if (newSuperview) {
        
        [self addCurImgView];
        [self addLeftImgView];
        [self addRightImgView];
        [self addPageControl];
    }
    
    [super willMoveToSuperview:newSuperview];
}

#pragma mark - SubView Handle

- (void)addCurImgView {
    [self addSubview:self.curImgView];
    
    self.curImgView.frame = CGRectMake(0.f, 0.f, self.frame.size.width, self.frame.size.height);
}

- (void)addLeftImgView {
    [self addSubview:self.leftImgView];
    
    self.leftImgView.frame = CGRectMake(-self.frame.size.width, 0.f, self.frame.size.width, self.frame.size.height);
}

- (void)addRightImgView {
    [self addSubview:self.rightImgView];
    
    self.rightImgView.frame = CGRectMake(self.frame.size.width, 0.f, self.frame.size.width, self.frame.size.height);
}

- (void)addPageControl {
    [self addSubview:self.pageControl];
    
    self.pageControl.frame = CGRectMake(0.f, self.frame.size.height-kHeightPageControl, self.frame.size.width, kHeightPageControl);
}

#pragma mark - UIGestureRecognizerDelegate

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    CGPoint point = [(UIPanGestureRecognizer *)gestureRecognizer translationInView:gestureRecognizer.view];
    if (point.x > 0) {
        if (_selectedIndex == 0) {
            return YES;
        }
    } else {
        if (_selectedIndex == _numberOfItems-1) {
            return NO;
        }
    }
    
    return NO;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    self.curImgView.frame = CGRectMake(0.f, 0.f, self.frame.size.width, self.frame.size.height);
    self.leftImgView.frame = CGRectMake(-self.frame.size.width, 0.f, self.frame.size.width, self.frame.size.height);
    self.rightImgView.frame = CGRectMake(self.frame.size.width, 0.f, self.frame.size.width, self.frame.size.height);
    self.pageControl.frame = CGRectMake(0.f, self.frame.size.height-kHeightPageControl, self.frame.size.width, kHeightPageControl);
}

#pragma mark - Setter and Getter

- (UIImageView *)leftImgView {
    if (!_leftImgView) {
        _leftImgView = [[UIImageView alloc] initWithFrame:CGRectMake(-self.frame.size.width, 0, self.frame.size.width, self.frame.size.height)];
        _leftImgView.userInteractionEnabled = YES;
        _leftImgView.contentMode = UIViewContentModeScaleAspectFit;
    }
    
    return _leftImgView;
}

- (UIImageView *)rightImgView {
    if (!_rightImgView) {
        _rightImgView = [[UIImageView alloc] initWithFrame:CGRectMake(self.frame.size.width, 0, self.frame.size.width, self.frame.size.height)];
        _rightImgView.userInteractionEnabled = YES;
        _rightImgView.contentMode = UIViewContentModeScaleAspectFit;
    }
    
    return _rightImgView;
}

- (UIImageView *)curImgView {
    if (!_curImgView) {
        _curImgView = [[UIImageView alloc] initWithFrame:CGRectMake(0.f, 0.f, self.frame.size.width, self.frame.size.height)];
        _curImgView.userInteractionEnabled = YES;
        _curImgView.contentMode = UIViewContentModeScaleAspectFit;
    }
    
    return _curImgView;
}

- (UIPageControl *)pageControl {
    if (!_pageControl) {
        _pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0.f, 0.f, self.frame.size.width, 20.f)];
        _pageControl.hidesForSinglePage = YES;
        _pageControl.pageIndicatorTintColor = [UIColor lightGrayColor];
        _pageControl.currentPageIndicatorTintColor = [UIColor whiteColor];
    }
    
    return _pageControl;
}

- (UIPanGestureRecognizer *)panGesture {
    if (!_panGesture) {
        _panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanGesture:)];
        _panGesture.delegate = self;
    }
    
    return _panGesture;
}

- (UITapGestureRecognizer *)tapGesture {
    if (!_tapGesture) {
        _tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGesture:)];
    }
    
    return _tapGesture;
}

- (void)setSelectedIndex:(NSInteger)selectedIndex {
    _selectedIndex = selectedIndex;
    
    self.pageControl.currentPage =_selectedIndex;
}

- (void)setDelegate:(id<YCAdViewDelegate>)delegate {
    _delegate = delegate;
    
    _numberOfItems = [_delegate numberOfItemsInAdView:self];
    
    if (_numberOfItems > 0 && _selectedIndex > -1 && _selectedIndex < _numberOfItems) {
        self.pageControl.numberOfPages = _numberOfItems;
        self.pageControl.currentPage = self.selectedIndex;
        
        [self.curImgView addGestureRecognizer:self.panGesture];
        [self.curImgView addGestureRecognizer:self.tapGesture];
        if ([self.delegate respondsToSelector:@selector(adView:configItemView:atIndex:)]) {
            [self.delegate adView:self configItemView:self.curImgView atIndex:self.selectedIndex];
        }
        
        if (_numberOfItems > 1) {
            if ([self.delegate respondsToSelector:@selector(adView:configItemView:atIndex:)]) {
                [self.delegate adView:self configItemView:self.leftImgView atIndex:(self.selectedIndex-1 < 0 ? _numberOfItems-1 : self.selectedIndex-1)];
            }
            if ([self.delegate respondsToSelector:@selector(adView:configItemView:atIndex:)]) {
                [self.delegate adView:self configItemView:self.rightImgView atIndex:(self.selectedIndex+1 == _numberOfItems ? 0 : self.selectedIndex+1)];
            }
        }
    }
}

- (void)setIntervalForTimer:(NSTimeInterval)intervalForTimer {
    _intervalForTimer = intervalForTimer;
    
    [self startTimer];
}

#pragma mark - Event Response

- (void)handleTapGesture:(UITapGestureRecognizer *)gesture {
    if ([self.delegate respondsToSelector:@selector(adView:didClickAtIndex:)]) {
        [self.delegate adView:self didClickAtIndex:self.selectedIndex];
    }
}

- (void)handlePanGesture:(UIPanGestureRecognizer *)gesture {
    if (gesture.state == UIGestureRecognizerStateBegan) {
        _leftImgView.frame = CGRectMake(-self.frame.size.width, 0.f, self.frame.size.width, self.frame.size.height);
        _rightImgView.frame = CGRectMake(self.frame.size.width, 0.f, self.frame.size.width, self.frame.size.height);
        
        [self stopTimer];
    } else if (gesture.state==UIGestureRecognizerStateCancelled || gesture.state==UIGestureRecognizerStateEnded) {
        CGPoint point = [gesture translationInView:gesture.view];
        if (point.x > 0) {
            if (point.x > kMaxDistanceForResponde && _numberOfItems > 1) {
                [self goLastPageByGesture];
            } else {
                [self goCurPage];
            }
        } else {
            if (fabs(point.x) > kMaxDistanceForResponde && _numberOfItems > 1) {
                [self goNextPageByGesture];
            } else {
                [self goCurPage];
            }
        }
        
        [self setIntervalForTimer:self.intervalForTimer];
    } else {
        CGPoint point = [gesture translationInView:gesture.view];
        
        [self handleGestureTranslation:point];
    }
}

- (void)handleGestureTranslation:(CGPoint)point {
    if (point.x < 0) {// 向左滑动
        if (self.selectedIndex == _numberOfItems - 1) {// 是最后一张
            // 通知
            if ([self.delegate respondsToSelector:@selector(adViewWillNextLoop:)]) {
                [self.delegate adViewWillNextLoop:self];
            }
            // 更新位置
            if (self.infiniteLoopEnable) {
                [self updatePositionByGesture:point];
            }
        } else {// 不是最后一张
            // 更新位置
            [self updatePositionByGesture:point];
        }
    } else if (point.x > 0) {// 向右滑动
        if (self.selectedIndex == 0) {// 是第一张
            // 通知
            if ([self.delegate respondsToSelector:@selector(adViewWillLastLoop:)]) {
                [self.delegate adViewWillLastLoop:self];
            }
            // 更新位置
            if (self.infiniteLoopEnable) {
                [self updatePositionByGesture:point];
            }
        } else {
            // 更新位置
            [self updatePositionByGesture:point];
        }
    }
}

/// 根据手势移动更新位置
- (void)updatePositionByGesture:(CGPoint)point {
    CGRect curRect = _curImgView.frame;
    curRect.origin.x = point.x;
    _curImgView.frame = curRect;
    
    CGRect leftRect = _leftImgView.frame;
    leftRect.origin.x = curRect.origin.x - self.frame.size.width;
    _leftImgView.frame = leftRect;
    
    CGRect rightRect = _rightImgView.frame;
    rightRect.origin.x = curRect.origin.x + self.frame.size.width;
    _rightImgView.frame = rightRect;
}

#pragma mark - Timer Control

- (void)startTimer {
    [self stopTimer];
    
    if (self.intervalForTimer > 0) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:self.intervalForTimer target:self selector:@selector(goNextPageByTimer) userInfo:nil repeats:YES];
    }
}

- (void)stopTimer {
    [self.timer invalidate];
    self.timer = nil;
}

#pragma mark - Control

- (void)goNextPageByTimer {
    if (self.timer) {
        if (self.selectedIndex == _numberOfItems - 1) {
            // 通知
            if ([self.delegate respondsToSelector:@selector(adViewWillNextLoop:)]) {
                [self.delegate adViewWillNextLoop:self];
            }
            if (self.infiniteLoopEnable) {
                [self goNextPage];
            }
        } else {
            [self goNextPage];
        }
    }
}

- (void)goNextPageByGesture {
    if (self.selectedIndex == _numberOfItems - 1) {
        // 通知
        if ([self.delegate respondsToSelector:@selector(adViewWillNextLoop:)]) {
            [self.delegate adViewWillNextLoop:self];
        }
        
        if (self.infiniteLoopEnable) {
            [self goNextPage];
        } else {
            [self goCurPage];
        }
    } else {
        [self goNextPage];
    }
}

- (void)goNextPage {
    // 跳转下一页动画
    [UIView animateWithDuration:kDuration
                     animations:^{
                         self.rightImgView.frame = CGRectMake(0.f, 0.f, self.frame.size.width, self.frame.size.height);
                         self.curImgView.frame = CGRectMake(-self.frame.size.width, 0.f, self.frame.size.width, self.frame.size.height);
                         
                     }
                     completion:^(BOOL finished) {
                         UIImageView *temp = self.curImgView;
                         [temp removeGestureRecognizer:self.panGesture];
                         [temp removeGestureRecognizer:self.tapGesture];
                         self.curImgView = self.rightImgView;
                         [self.curImgView addGestureRecognizer:self.panGesture];
                         [self.curImgView addGestureRecognizer:self.tapGesture];
                         self.rightImgView = self.leftImgView;
                         self.leftImgView = temp;
                         
                         self.selectedIndex++;
                         if (self.selectedIndex == _numberOfItems) {
                             self.selectedIndex = 0;
                         }
                         
                         self.rightImgView.frame = CGRectMake(self.frame.size.width, 0.f, self.frame.size.width, self.frame.size.height);
                         
                         if ([self.delegate respondsToSelector:@selector(adView:configItemView:atIndex:)]) {
                             [self.delegate adView:self configItemView:self.rightImgView atIndex:(self.selectedIndex+1 == _numberOfItems ? 0 : self.selectedIndex+1)];
                         }
                     }];
}

- (void)goLastPageByGesture {
    if (self.selectedIndex == 0) {
        if (self.infiniteLoopEnable) {
            [self goLastPage];
        } else {
            [self goCurPage];
        }
    } else {
        [self goLastPage];
    }
}

- (void)goLastPage {
    // 跳转上一页动画
    [UIView animateWithDuration:kDuration
                     animations:^{
                         self.leftImgView.frame = CGRectMake(0.f, 0.f, self.frame.size.width, self.frame.size.height);
                         self.curImgView.frame = CGRectMake(self.frame.size.width, 0.f, self.frame.size.width, self.frame.size.height);
                         
                     }
                     completion:^(BOOL finished) {
                         UIImageView *temp = self.curImgView;
                         [temp removeGestureRecognizer:self.panGesture];
                         [temp removeGestureRecognizer:self.tapGesture];
                         self.curImgView = self.leftImgView;
                         [self.curImgView addGestureRecognizer:self.panGesture];
                         [self.curImgView addGestureRecognizer:self.tapGesture];
                         self.leftImgView = self.rightImgView;
                         self.rightImgView = temp;
                         
                         self.selectedIndex--;
                         if (self.selectedIndex < 0) {
                             self.selectedIndex = _numberOfItems-1;
                         }
                         
                         self.leftImgView.frame = CGRectMake(-self.frame.size.width, 0.f, self.frame.size.width, self.frame.size.height);
                         
                         if ([self.delegate respondsToSelector:@selector(adView:configItemView:atIndex:)]) {
                             [self.delegate adView:self configItemView:self.leftImgView atIndex:(self.selectedIndex-1 < 0 ? _numberOfItems-1 : self.selectedIndex-1)];
                         }
                     }];
}

- (void)goCurPage {
    [UIView animateWithDuration:kDuration
                     animations:^{
                         self.curImgView.frame = CGRectMake(0.f, 0.f, self.frame.size.width, self.frame.size.height);
                         self.rightImgView.frame = CGRectMake(self.frame.size.width, 0.f, self.frame.size.width, self.frame.size.height);
                         self.leftImgView.frame = CGRectMake(-self.frame.size.width, 0.f, self.frame.size.width, self.frame.size.height);
                     }
                     completion:^(BOOL finished) {
                         
                     }];
}

#pragma mark - Public Methods

- (void)reloadData {
    self.delegate = self.delegate;
}

@end
